import requests

# 高德 API 配置
AMAP_KEY = ""  # 替换为你的高德 API Key
DISTRICT_URL = "https://restapi.amap.com/v3/config/district"

def get_citycode(city_name):
    """根据城市名称获取 citycode"""
    params = {
        "key": AMAP_KEY,
        "keywords": city_name,
        "subdistrict": 2  # 查询层级
    }
    try:
        response = requests.get(DISTRICT_URL, params=params)
        data = response.json()
        if data["status"] == "1" and len(data["districts"]) > 0:
            return data["districts"][0]["citycode"]  # citycode 在 districts 中
        return None
    except Exception as e:
        print(f"请求失败: {e}")
        return None

# 测试
city_name = "北京"
citycode = get_citycode(city_name)
print(f"{city_name} 的 citycode: {citycode}")
